<template>
	<view class="tech-dashboard">
		<!-- 个人状态卡片 -->
		<view class="status-card">
			<view class="avatar-section">
				<view class="avatar">
					<text class="avatar-text">{{ userInfo.realName ? userInfo.realName.charAt(0) : 'T' }}</text>
				</view>
				<view class="user-info">
					<text class="name">{{ userInfo.realName || userInfo.username }}</text>
					<text class="role">技术员</text>
				</view>
			</view>
			
			<view class="status-toggle">
				<text class="status-label">工作状态</text>
				<switch 
					:checked="isAvailable" 
					@change="toggleStatus"
					color="#007AFF"
				/>
				<text class="status-text" :class="{ available: isAvailable }">
					{{ isAvailable ? '空闲中' : '忙碌中' }}
				</text>
			</view>
		</view>
		
		<!-- 统计数据 -->
		<view class="stats-section">
			<view class="stat-item">
				<text class="stat-number">{{ stats.currentOrders || 0 }}</text>
				<text class="stat-label">进行中</text>
			</view>
			<view class="stat-item">
				<text class="stat-number">{{ stats.completedOrders || 0 }}</text>
				<text class="stat-label">已完成</text>
			</view>
			<view class="stat-item">
				<text class="stat-number">{{ stats.totalEarnings || 0 }}</text>
				<text class="stat-label">总收入</text>
			</view>
			<view class="stat-item">
				<text class="stat-number">{{ stats.rating || 5.0 }}</text>
				<text class="stat-label">评分</text>
			</view>
		</view>
		
		<!-- 快捷操作 -->
		<view class="quick-actions">
			<view class="action-item" @click="goAvailableOrders">
				<view class="action-icon available-icon">📋</view>
				<text class="action-text">可接订单</text>
				<text class="action-count" v-if="availableCount > 0">{{ availableCount }}</text>
			</view>
			
			<view class="action-item" @click="goMyOrders">
				<view class="action-icon my-icon">📊</view>
				<text class="action-text">我的订单</text>
			</view>
			
			<view class="action-item" @click="goEarnings">
				<view class="action-icon earning-icon">💰</view>
				<text class="action-text">收入明细</text>
			</view>
			
			<view class="action-item" @click="goProfile">
				<view class="action-icon profile-icon">👤</view>
				<text class="action-text">个人资料</text>
			</view>
		</view>
		
		<!-- 最新订单 -->
		<view class="recent-orders">
			<view class="section-title">
				<text>最新订单</text>
				<text class="more" @click="goMyOrders">查看全部</text>
			</view>
			
			<view class="order-list">
				<view class="order-item" v-for="order in recentOrders" :key="order.id" @click="goOrderDetail(order.id)">
					<view class="order-header">
						<text class="order-title">{{ order.title }}</text>
						<text class="order-status" :class="getStatusClass(order.status)">
							{{ getStatusText(order.status) }}
						</text>
					</view>
					
					<view class="order-info">
						<view class="info-item">
							<text class="label">预算：</text>
							<text class="value budget">￥{{ order.budget }}</text>
						</view>
						<view class="info-item">
							<text class="label">分类：</text>
							<text class="value">{{ order.categoryName }}</text>
						</view>
						<view class="info-item">
							<text class="label">截止：</text>
							<text class="value">{{ formatTime(order.deadline) }}</text>
						</view>
					</view>
					
					<view class="order-actions" v-if="order.status === 2">
						<button class="action-btn complete" @click.stop="completeOrder(order.id)">
							标记完成
						</button>
					</view>
				</view>
				
				<view class="empty" v-if="recentOrders.length === 0">
					<text>暂无订单数据</text>
				</view>
			</view>
		</view>
		
		<!-- 技能标签 -->
		<view class="skills-section">
			<view class="section-title">我的技能</view>
			<view class="skills-list">
				<text class="skill-tag" v-for="skill in skills" :key="skill">{{ skill }}</text>
				<text class="add-skill" @click="editSkills">+</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userInfo: {},
				stats: {},
				recentOrders: [],
				skills: [],
				isAvailable: true,
				availableCount: 0,
				loading: false
			}
		},
		onLoad() {
			this.checkPermission()
			this.loadDashboardData()
		},
		onShow() {
			this.loadDashboardData()
		},
		methods: {
			checkPermission() {
				if (!this.$store || !this.$store.getters.isTech) {
					uni.showToast({
						title: '权限不足',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
					return false
				}
				return true
			},
			
			async loadDashboardData() {
				this.loading = true
				try {
					await Promise.all([
						this.loadUserInfo(),
						this.loadStats(),
						this.loadRecentOrders(),
						this.loadSkills(),
						this.loadAvailableCount()
					])
				} catch (error) {
					console.error('加载数据失败:', error)
				} finally {
					this.loading = false
				}
			},
			
			async loadUserInfo() {
				try {
					const res = await this.$api.getUserInfo()
					if (res.code === 200) {
						this.userInfo = res.data
						this.isAvailable = res.data.status === 'available'
					}
				} catch (error) {
					console.error('加载用户信息失败:', error)
				}
			},
			
			async loadStats() {
				try {
					const res = await this.$api.getTechStats()
					if (res.code === 200) {
						this.stats = res.data
					}
				} catch (error) {
					console.error('加载统计数据失败:', error)
				}
			},
			
			async loadRecentOrders() {
				try {
					const res = await this.$api.getMyOrders({ pageSize: 5 })
					if (res.code === 200) {
						this.recentOrders = res.data || []
					}
				} catch (error) {
					console.error('加载最新订单失败:', error)
				}
			},
			
			async loadSkills() {
				try {
					// 从用户信息中获取技能标签
					if (this.userInfo.skills) {
						this.skills = this.userInfo.skills.split(',').filter(s => s.trim())
					} else {
						this.skills = ['Web开发', 'Vue.js', 'JavaScript']
					}
				} catch (error) {
					console.error('加载技能标签失败:', error)
				}
			},
			
			async loadAvailableCount() {
				try {
					const res = await this.$api.getOrderList({ status: 1, pageSize: 1 })
					if (res.code === 200) {
						this.availableCount = res.total || 0
					}
				} catch (error) {
					console.error('加载可接订单数量失败:', error)
				}
			},
			
			async toggleStatus(e) {
				const newStatus = e.detail.value
				try {
					await this.$api.updateTechStatus({ 
						status: newStatus ? 'available' : 'busy' 
					})
					this.isAvailable = newStatus
					uni.showToast({
						title: newStatus ? '已设为空闲' : '已设为忙碌',
						icon: 'success'
					})
				} catch (error) {
					uni.showToast({
						title: error.message || '状态更新失败',
						icon: 'none'
					})
					// 恢复原状态
					this.isAvailable = !newStatus
				}
			},
			
			goAvailableOrders() {
				uni.switchTab({
					url: '/pages/order/list?status=1&available=true'
				})
			},
			
			goMyOrders() {
				uni.navigateTo({
					url: '/pages/tech/orders'
				})
			},
			
			goEarnings() {
				uni.navigateTo({
					url: '/pages/tech/earnings'
				})
			},
			
			goProfile() {
				uni.switchTab({
					url: '/pages/user/profile'
				})
			},
			
			goOrderDetail(id) {
				uni.navigateTo({
					url: `/pages/order/detail?id=${id}`
				})
			},
			
			async completeOrder(id) {
				uni.showModal({
					title: '确认完成',
					content: '确定要标记此订单为完成状态吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								await this.$api.completeOrder(id)
								uni.showToast({
									title: '标记成功',
									icon: 'success'
								})
								this.loadRecentOrders()
							} catch (error) {
								uni.showToast({
									title: error.message || '操作失败',
									icon: 'none'
								})
							}
						}
					}
				})
			},
			
			editSkills() {
				uni.showToast({
					title: '功能开发中',
					icon: 'none'
				})
			},
			
			getStatusClass(status) {
				const statusMap = {
					1: 'status-pending',
					2: 'status-processing',
					3: 'status-reviewing',
					4: 'status-completed',
					5: 'status-cancelled'
				}
				return statusMap[status] || ''
			},
			
			getStatusText(status) {
				const statusMap = {
					1: '待接单',
					2: '进行中',
					3: '待验收',
					4: '已完成',
					5: '已取消'
				}
				return statusMap[status] || '未知'
			},
			
			formatTime(time) {
				if (!time) return ''
				const date = new Date(time)
				const now = new Date()
				const diff = now - date
				
				if (diff < 0) {
					const days = Math.ceil(-diff / (1000 * 60 * 60 * 24))
					return `${days}天后`
				}
				
				if (diff < 60000) return '刚刚'
				if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
				if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'
				return Math.floor(diff / 86400000) + '天前'
			}
		}
	}
</script>

<style lang="scss" scoped>
	.tech-dashboard {
		background: #f5f5f5;
		min-height: 100vh;
		padding: 20rpx;
	}
	
	.status-card {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		border-radius: 20rpx;
		padding: 40rpx;
		margin-bottom: 30rpx;
		color: #fff;
		
		.avatar-section {
			display: flex;
			align-items: center;
			margin-bottom: 30rpx;
			
			.avatar {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50rpx;
				background: rgba(255, 255, 255, 0.2);
				display: flex;
				align-items: center;
				justify-content: center;
				margin-right: 30rpx;
				
				.avatar-text {
					font-size: 36rpx;
					font-weight: bold;
					color: #fff;
				}
			}
			
			.user-info {
				flex: 1;
				
				.name {
					display: block;
					font-size: 36rpx;
					font-weight: bold;
					margin-bottom: 10rpx;
				}
				
				.role {
					font-size: 24rpx;
					opacity: 0.8;
				}
			}
		}
		
		.status-toggle {
			display: flex;
			align-items: center;
			justify-content: space-between;
			
			.status-label {
				font-size: 28rpx;
			}
			
			.status-text {
				font-size: 24rpx;
				opacity: 0.8;
				
				&.available {
					color: #4CAF50;
				}
			}
		}
	}
	
	.stats-section {
		display: flex;
		background: #fff;
		border-radius: 15rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		
		.stat-item {
			flex: 1;
			text-align: center;
			
			&:not(:last-child) {
				border-right: 1rpx solid #f0f0f0;
			}
			
			.stat-number {
				display: block;
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 10rpx;
			}
			
			.stat-label {
				font-size: 24rpx;
				color: #666;
			}
		}
	}
	
	.quick-actions {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		margin-bottom: 30rpx;
		
		.action-item {
			flex: 1;
			min-width: 160rpx;
			background: #fff;
			border-radius: 15rpx;
			padding: 40rpx 20rpx;
			text-align: center;
			box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
			position: relative;
			
			.action-icon {
				width: 80rpx;
				height: 80rpx;
				border-radius: 40rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 0 auto 20rpx;
				font-size: 36rpx;
				
				&.available-icon {
					background: linear-gradient(45deg, #ff9500, #ff5722);
				}
				
				&.my-icon {
					background: linear-gradient(45deg, #007AFF, #0056CC);
				}
				
				&.earning-icon {
					background: linear-gradient(45deg, #34c759, #28a745);
				}
				
				&.profile-icon {
					background: linear-gradient(45deg, #5856d6, #4a4a8a);
				}
			}
			
			.action-text {
				font-size: 24rpx;
				color: #666;
			}
			
			.action-count {
				position: absolute;
				top: 20rpx;
				right: 20rpx;
				background: #ff3b30;
				color: #fff;
				font-size: 20rpx;
				padding: 4rpx 8rpx;
				border-radius: 10rpx;
				min-width: 32rpx;
				text-align: center;
			}
		}
	}
	
	.recent-orders, .skills-section {
		background: #fff;
		border-radius: 15rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		
		.more {
			font-size: 24rpx;
			color: #007AFF;
			font-weight: normal;
		}
	}
	
	.order-list {
		.order-item {
			border: 1rpx solid #f0f0f0;
			border-radius: 10rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;
			
			&:last-child {
				margin-bottom: 0;
			}
			
			.order-header {
				display: flex;
				justify-content: space-between;
				align-items: flex-start;
				margin-bottom: 20rpx;
				
				.order-title {
					flex: 1;
					font-size: 28rpx;
					font-weight: bold;
					color: #333;
					margin-right: 20rpx;
				}
				
				.order-status {
					font-size: 24rpx;
					padding: 6rpx 16rpx;
					border-radius: 15rpx;
					white-space: nowrap;
				}
			}
			
			.order-info {
				margin-bottom: 20rpx;
				
				.info-item {
					display: flex;
					margin-bottom: 10rpx;
					
					&:last-child {
						margin-bottom: 0;
					}
					
					.label {
						font-size: 24rpx;
						color: #666;
						width: 80rpx;
					}
					
					.value {
						flex: 1;
						font-size: 24rpx;
						color: #333;
						
						&.budget {
							font-weight: bold;
							color: #FF6B6B;
						}
					}
				}
			}
			
			.order-actions {
				.action-btn {
					width: 100%;
					height: 60rpx;
					border: none;
					border-radius: 30rpx;
					font-size: 24rpx;
					
					&.complete {
						background: #34c759;
						color: #fff;
					}
				}
			}
		}
		
		.empty {
			text-align: center;
			padding: 80rpx 0;
			color: #999;
			font-size: 28rpx;
		}
	}
	
	.skills-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		
		.skill-tag {
			background: #f0f0f0;
			color: #666;
			font-size: 24rpx;
			padding: 10rpx 20rpx;
			border-radius: 20rpx;
		}
		
		.add-skill {
			background: #007AFF;
			color: #fff;
			font-size: 24rpx;
			padding: 10rpx 20rpx;
			border-radius: 20rpx;
			width: 60rpx;
			text-align: center;
		}
	}
</style>